<?php
/**
 * $Id: LocalScope.class.php 264 2009-03-22 06:29:51Z coretxt $
 * @package repository
 * @subpackage store
 *
 * Copyright (c) 2007-2009 Coretxt
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * An identity map containing objects in the scope of the
 * current request.
 * 
 * If an object already exists in scope then no round trip is
 * required to retrieve it.
 *
 * @package repository
 * @subpackage store
 */
class LocalScope {
	
	/**
	 * Singleton static instance.
	 */
	static private $self;
	
	/**
	 * Map of current objects.
	 */
	private $map;

	/**
	 * Constructor expects to be passed a storage gateway.
	 */
	function __construct($storage) {
		$this->storage = $storage;
		$this->new = array();
		$this->map = array();
	}
	
	/**
	 * Returns a single static instance of the identity map.
	 */
	function instance() {
		if (!isset(self::$self)) {
			self::$self = new LocalScope(new MysqlGateway(new MysqlConnection));
		}
		return self::$self;
	}
	
	/**
	 * Looks up an object by id. If it doesn't exist in memory, it will be
	 * retrieved from the database.
	 */
	function selectById($table, $id) {
		if (!isset($this->map[$table][$id])) {
			$this->storage->selectById($table, $id);
			$this->map[$table][$id] = $this->storage->getArray();
		}
		return $this->map[$table][$id];
	}
	
	/**
	 * Removes a record from the identity map.
	 */
	function remove($table, $id) {
		unset($this->map[$table][$id]);
	}
	
	/**
	 * Saves an item persistently and assigns autogenerated id as key.
	 */
	function save($table, $properties) {
		if (!isset($properties['id'])) {
			$this->storage->insert($table, $properties);
			$id = $this->storage->insertId();
			$properties['id'] = $id;
		} else {
			$id = $properties['id'];
			$this->storage->update($table, array('id'=>$id), $properties);
		}
		$this->map[$table][$id] = $properties;
		return $properties;
	}
}

?>